#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/wait.h>

// 父进程读
void FatherRead(int rfd)
{
    char buffer[1024];
    while (true)
    {
        size_t size = read(rfd, buffer, sizeof(buffer));
        if (size > 0)
        {
            // sleep(3);
            std::cout << "father read: " << buffer << std::endl;
            sleep(2);
        }
        else
        {
            std::cout << "child exit, i am exit:" << std::endl;
            break;
        }
    }
}

// 子进程写
void ChildWrite(int wfd)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "child send to father");
    int cnt = 0;
    int c = 10;
    while (c--)
    {
        sleep(1000);
        int num = write(wfd, buffer, sizeof(buffer));
        if (num > 0)
        {
            std::cout << "Child have write:" << cnt++ << "times->" << buffer << std::endl;
        }
        else
        {
            break;
        }
    }
}

int main()
{
    // 创建管道
    int fd[2] = {0}; // fd[0]读端，fd[1]写端
    int n = pipe(fd);
    if (n < 0)
    {
        // 创建管道失败
        return 1;
    }
    // 1. 创建子进程
    pid_t id = fork();
    if (id < 0)
    {
        // 创建失败
        return -1;
    }
    else if (id == 0)
    {
        // child
        // 关闭写读端
        close(fd[0]);
        ChildWrite(fd[1]);
        // 写完之后关闭
        close(fd[1]);
    }
    // father
    //  父进程关闭写端
    close(fd[1]);
    FatherRead(fd[0]);
    close(fd[1]);

    // 回收子进程
    pid_t subid = waitpid(id, nullptr, 0);

    return 0;
}
